import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { showFailToast } from 'vant';
import { getToken, clearToken } from '@/utils/auth';
import baseUrl from './getBaseUrl';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number | string;
  data: T;
  rows: T;
}

export const config = {
  baseURL: baseUrl,
  timeout: 180000,
};

export const interceptorsRequest = (_config: AxiosRequestConfig) => {
  const token = getToken();
  if (token) {
    _config.headers = {
      ...(_config?.headers || {}),
      Authorization: `Bearer ${token}`,
    };
  }
  return _config;
};

export const interceptorsRequestError = (error: any) => {
  // do something
  return Promise.reject(error);
};

export function errorHandle(error: { response: any }, hideTip = false) {
  const msg = error?.response?.data?.message;
  const code = error?.response?.data?.code;
  if (code) {
    if (code === 401) {
      showFailToast('登录失效，请重新登录');
      clearToken();
      window.location.reload();
    } else if (!hideTip) {
      showFailToast(msg || '请求失败，请稍后重试!');
    }
  } else if (!hideTip) {
    showFailToast(msg || '请求失败，请稍后重试!');
  }
}

export const interceptorsResponse = (
  response: AxiosResponse<HttpResponse>,
  hideHandle?: boolean
) => {
  const { data } = response;
  if (data.code !== 200) {
    const obj = {
      from: 'http',
      response,
    };
    if (!hideHandle) {
      errorHandle(obj);
    }
    return Promise.reject(obj);
  }

  return data;
};

export const interceptorsResponseError = (error: any, hideTip?: boolean) => {
  if (!error?.from) {
    errorHandle(error, hideTip);
  }
  return Promise.reject(error.response.data);
};
